package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.PageParam;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/dish")
@RestController
public class DishController {

    @Autowired
    private DishService ds;

    /**
     * 根据分类的id，获取菜品数据
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public R list(long categoryId, Integer status) {

        try {
            //1. 调用service
//            List<Dish> list = ds.findByCategoryId(categoryId , status);
            List<DishDto> list = ds.findByCategoryId(categoryId, status);

            return R.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败！");
        }

    }

    /**
     * 更新菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {

        int row = ds.update(dishDto);
        if (row > 0) {
            return R.success("更新成功!");
        } else {
            return R.error("更新失败！");
        }

    }

    /**
     * 分页查询菜品
     *
     * @param pageParam
     * @return
     */
    @GetMapping("/page")
    public R findPage(PageParam pageParam) {

        try {
            //1. 调用service
            IPage<DishDto> page = ds.findPage(pageParam);

            //2. 返回数据
            return R.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("分页查询失败！");
        }
    }


    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R add(@RequestBody DishDto dishDto) {
        System.out.println("dishDto = " + dishDto);

        //1. 调用service
        int row = ds.add(dishDto);

        //2. 返回
        if (row > 0) {
            return R.success("添加菜品成功！");
        } else {
            return R.error("添加菜品失败！");
        }

    }

    @DeleteMapping
    public R deleGroup(@RequestParam List<Long> ids) {
        int rows = ds.deleGroup(ids);
        if (rows != 0) {
            return R.success(rows);
        } else {
            return R.error("批量删除失败");
        }
    }

    @PostMapping("/status/{status}")
    public R StatusChange(@PathVariable Integer status, @RequestParam List<Long> ids) {
        int row = ds.StatusChange(status, ids);
        if (row > 0) {
            return R.success("success...");
        } else {
            return R.error("批量状态更改失败");
        }
    }
}